//
//  ViewController.m
//  AnyMeetUIKit
//
//  Created by derek on 2018/4/27.
//  Copyright © 2018年 derek. All rights reserved.
//

#import "ViewController.h"
#import "AnyMeetVideoController.h"
#import "AMDocBlockView.h"



@interface ViewController ()<AnyMeetPicShearDataSource>
@property (weak, nonatomic) IBOutlet UILabel *accountLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) AMUserModel *userModel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //模拟用户
    self.userModel = [[AMUserModel alloc] init];
    self.userModel.userId = @"1234";
    self.userModel.userName = @"张三";
    self.userModel.userHeadUrl = @"http://www.kutx.cn/xiaotupian/icons/png/200803/20080327095245737.png";
    
    self.dataArray = [[NSMutableArray alloc] initWithCapacity:4];
    
}
// 接口验证
- (IBAction)doSomeEvent:(id)sender {
   
    UIButton *button = (UIButton*)sender;
    __weak typeof(self)weakSelf = self;
    [ASHUD showHUDWithLoadingStyleInView:self.view belowView:nil content:@""];
    switch (button.tag) {
        case 200:
        {
            // 账号对接
            [[AMApiManager shareInstance] registeredDockingMeeting:self.userModel success:^(int code) {
                [ASHUD hideHUD];
                if (code==200) {
                    //成功
                    weakSelf.accountLabel.text = [NSString stringWithFormat:@"我的账号ID:%@",weakSelf.userModel.userId];
                }else{
                    
                }
            } failure:^(NSError *error) {
                [ASHUD hideHUD];
            }];
        }
            break;
        case 201:
        {
            int type = arc4random()%3;
            type = 2;
            switch (type) {
                case 0:
                {
                      // 创建开放会议
                    [[AMApiManager shareInstance] createMeetingRoom:[self getMeetingName] withMeetType:AMMeetTypeNomal withMeetStartTime:[AMCommon getTimestamp] withPassWord:nil withLimitType:AMMeetLimitOpenType withDefaultPersonList:nil success:^(int code) {
                        [ASHUD hideHUD];
                        if (code !=200) {
                            [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
                        }
                    } failure:^(NSError *error) {
                        [ASHUD hideHUD];
                    }];
                }
                    break;
                case 1:
                {
                    // 创建密码会议
                    [[AMApiManager shareInstance] createMeetingRoom:[self getMeetingName] withMeetType:AMMeetTypeNomal withMeetStartTime:[AMCommon getTimestamp] withPassWord:@"123456" withLimitType:AMMeetLimitPassWordType withDefaultPersonList:nil success:^(int code) {
                        [ASHUD hideHUD];
                        if (code !=200) {
                            [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
                        }
                    } failure:^(NSError *error) {
                        [ASHUD hideHUD];
                    }];
                }
                    break;
                case 2:
                {
                    //确保用户123,和456在平台上注册
                    NSArray *arrayList = [[NSArray alloc] initWithObjects:@"123",@"456", nil];
                    // 创建邀请会议
                    [[AMApiManager shareInstance] createMeetingRoom:[self getMeetingName] withMeetType:AMMeetTypeNomal withMeetStartTime:[AMCommon getTimestamp] withPassWord:nil withLimitType:AMMeetLimitDefaultPersonType withDefaultPersonList:arrayList success:^(int code) {
                        [ASHUD hideHUD];
                        if (code !=200) {
                             [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
                        }
                       
                    } failure:^(NSError *error) {
                        [ASHUD hideHUD];
                    }];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        case 202:
        {
            // 获取会议列表
            [[AMApiManager shareInstance] getUserMeetingListWithPageNum:1 withPageSize:20 success:^(AMMeetListModel *model, int code) {
                 [ASHUD hideHUD];
                if (code == 200) {
                    weakSelf.dataArray = [model.meetinglist mutableCopy];
                    [weakSelf.tableView reloadData];
                }else{
                   [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
                }
            } failure:^(NSError *error) {
                [ASHUD hideHUD];
            }];
         
        }
            break;
        case 203:
        {
            //加入一个会议
            [ASHUD hideHUD];
            //密码
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"加入会议" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                textField.placeholder = @"会议ID";
            }];
            
            //确定
            UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                UITextField *login = alertController.textFields.firstObject;
                [self veriftyMeet:login.text];
            }];
            [alertController addAction:sureAction];
            
            //确定
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
            [alertController addAction:cancleAction];
            
            [weakSelf presentViewController:alertController animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}


//取会议名字
- (NSString*)getMeetingName {
    return [NSString stringWithFormat:@"我的会议室:%d",arc4random()%10000];
}
- (IBAction)start:(id)sender {

//    AMDocBlockView *docView = [[AMDocBlockView alloc] initWithDoc:nil withHost:YES withDocItem:nil];
//    [self.view addSubview:docView];
//    [docView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
//    }];
}
#pragma mark -
#pragma mark - UITableViewDelegate UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    if (cell==NULL) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cellIdentifier"];
    }
    Meetinglist *model = [self.dataArray objectAtIndex:indexPath.row];
    NSString *typeStr;
    switch (model.m_limit_type) {
        case 0:
            typeStr = @"公开";
            break;
        case 1:
            typeStr = @"密码";
            break;
        case 2:
            typeStr = @"指定人员";
            break;
        default:
            break;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@(类型:%@)",model.m_name,typeStr];
    cell.detailTextLabel.text = model.meetingid;
    
    return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    Meetinglist *model = [self.dataArray objectAtIndex:indexPath.row];
    NSMutableArray  *btnArray = [NSMutableArray array];
    // 添加一个删除按钮
    __weak typeof(self)weakSelf = self;
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [ASHUD showHUDWithStayLoadingStyleInView:self.view belowView:nil content:@""];
        [[AMApiManager shareInstance] deleteMeetingRoom:model.meetingid success:^(int code) {
            [ASHUD hideHUD];
            if (code ==200) {
                // 1. 移除一行
                [weakSelf.dataArray removeObjectAtIndex:indexPath.row];
                // 2. 更新UI
                [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
            }
        } failure:^(NSError *error) {
            [ASHUD hideHUD];
        }];
    }];
    // 设置背景颜色
    deleteRowAction.backgroundColor = [UIColor redColor];
    
    // 添加一个编辑按钮
    UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"更新时间" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        [ASHUD showHUDWithStayLoadingStyleInView:self.view belowView:nil content:@""];
        [[AMApiManager shareInstance] updateMeetingStartTime:model.meetingid withUpdateStartTime:[AMCommon getTimestamp] success:^(int code) {
             [ASHUD hideHUD];
            if (code == 200) {
                // 一个动画
                [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
            }else{
                [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
            }
        } failure:^(NSError *error) {
             [ASHUD hideHUD];
        }];
    }];
    // 设置背景颜色
    editRowAction.backgroundColor = [UIColor blueColor];
    // 将按钮们加入数组
    [btnArray addObject:deleteRowAction];
    [btnArray addObject:editRowAction];
    
    return btnArray;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];// 取消
    
    Meetinglist *list = [self.dataArray objectAtIndex:indexPath.row];
    [self veriftyMeet:list.meetingid];
    
}
//验证权限
- (void)veriftyMeet:(NSString*)meetId {
    __weak typeof(self)weakSelf = self;
    [ASHUD showHUDWithStayLoadingStyleInView:self.view belowView:nil content:@""];
    //进会(获取会议详情)
    [[AMApiManager shareInstance] getMeetingInfo:meetId success:^(AMMeetInfoModel *model, int code) {
        [ASHUD hideHUD];
        if (code == 200) {
            //如果会议室锁定，则不能进入
            if (model.meetinginfo.m_is_lock) {
                [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:@"房间已经锁定，不能进入" icon:nil];
            }else{
                switch (model.meetinginfo.m_limit_type) {
                    case 0:
                    {
                        //开放的
                        [weakSelf inMeet:model];
                    }
                        break;
                    case 1:
                    {
                        //密码
                        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"输入密码" message:nil preferredStyle:UIAlertControllerStyleAlert];
                        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
                            textField.placeholder = @"密码";
                        }];
                        //确定
                        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
                            UITextField *login = alertController.textFields.firstObject;
                            if ([login.text isEqualToString:model.meetinginfo.m_password]) {
                                [weakSelf inMeet:model];
                            }else{
                                [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:@"密码错误" icon:nil];
                                login.text = @"";
                            }
                        }];
                        [alertController addAction:sureAction];
                        
                        //确定
                        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
                        [alertController addAction:cancleAction];
                        
                        [weakSelf presentViewController:alertController animated:YES completion:nil];
                        
                    }
                        break;
                    case 2:
                    {
                        //指定人员或者自己能进入房间
                        BOOL canEnter = NO;
                        //自己做对比
                        if ([[AMApiManager shareInstance].anyUserId isEqualToString:model.meetinginfo.m_userid]) {
                            canEnter = YES;
                        }else{
                            //邀请人员对比
                            for (Memberlist *memberItem in model.memberlist) {
                                if ([memberItem.mem_userid isEqualToString:weakSelf.userModel.userId]) {
                                    canEnter = YES;
                                    break;
                                }
                            }
                        }
                        if (canEnter) {
                            [weakSelf inMeet:model];
                        }else{
                            [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:@"对不起，内定房间号，您不能进入" icon:nil];
                        }
                    }
                        break;
                    default:
                        break;
                }
            }
        }else{
            //获取失败
            [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:[[AMApiManager shareInstance] getErrorInfoWithCode:code] icon:nil];
        }
    } failure:^(NSError *error) {
        [ASHUD hideHUD];
        [ASHUD showHUDWithCompleteStyleInView:weakSelf.view content:@"错误了，请检测原因" icon:nil];
    }];
}


- (void)inMeet:(AMMeetInfoModel*)meetModel {
    AnyMeetVideoController *videoController = [AnyMeetVideoController new];
    videoController.meetModel = meetModel;
    videoController.userModel = self.userModel;
    __weak typeof(self)weakSelf = self;
    __weak AnyMeetVideoController *tempVideoController = videoController;
    videoController.uploadBlock = ^(NSArray *picArray) {
       [weakSelf uploadPics:picArray withController:tempVideoController];
    };
    [self.navigationController pushViewController:videoController animated:YES];
}
- (void)uploadPics:(NSArray*)picArray withController:(AnyMeetVideoController*)controller {
    //    //选择图片（并上传，这里不再上传，自己上传自己的业务服务器）eg:假设已经上传成功
    NSArray *picArrayEg = @[@"http://h.hiphotos.baidu.com/image/pic/item/a5c27d1ed21b0ef48c509cecd1c451da80cb3ec3.jpg",@"http://d.hiphotos.baidu.com/image/pic/item/f11f3a292df5e0fe2a436547506034a85edf7219.jpg"];
    // 图片在自己服务器中的ID
    NSString *fileId = [AMCommon randomString:12];
    
    if (controller) {
        [controller gotoShearPics:picArrayEg withFileId:fileId];
    }
}
#pragma mark - AnyMeetPicShearDataSource
-(void)anyMeetPicShearSelectedPics:(NSArray *)picArray {
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
